<?php
namespace app\common\service\SmsService;

use app\model\BbcModel\SmsCode;
use app\model\BbcModel\ConfigChannel;
use app\Normal;

class SmsCodeService
{
    private $expir_time=30000;
    /**
    * 验证手机短信验证码
    * @param    array $param
    * @access   public
    * @return   array
    */
    public function validate(array $param = []):array
    {
        if (empty($param['mobile'])) {
            return Normal::returnCode(Normal::FAIL,"手机号不能为空");
        }
        
        if (empty($param['code'])) {
            return Normal::returnCode(Normal::FAIL,"短信验证码不能为空");
        }
        
        $where = [
            ['mobile', '=', $param['mobile']],
            ['status', '=', 0],
            ['cd', '>=', time()-$this->expir_time],
            '_order_' => 'id desc',
        ];
        $sms_code = SmsCode::instance()->info($where);
        
        if (empty($sms_code)) {
            return Normal::returnCode(Normal::FAIL,"请发送短信验证码");
        }
        
        if ($param['code'] != $sms_code['code']) {
            return Normal::returnCode(Normal::FAIL,"短信验证码错误");
        }
        SmsCode::instance()->edit(['id'=>$sms_code['id']],['status'=>1]);
        return Normal::returnCode(Normal::SUC,"验证通过");
    }
    /**
    * 发送验证码(无图形)
    * @param    array
    * @access   public
    * @return   array
    */
    public function sendSmsCodeNotImg(array $param = []):array
    {
        if (empty($param['mobile'])) {
            return Normal::returnCode(Normal::FAIL,"手机号不能为空");
        }
        if (empty($param['cid'])) {
            return Normal::returnCode(Normal::FAIL,"cid不能为空");
        }
        $temp      = !empty($param['temp']) ? $param['temp'] : '';
        $cache_key = "SmsCode_SendSmsCode_{$param['mobile']}_{$temp}";
        $redis = getRedisObj();
        $send_times= $redis->get($cache_key) ? $redis->get($cache_key) : 0;
        if (!empty($send_times) && $send_times>=3) {
            return Normal::returnCode(Normal::FAIL,"操作频繁");
        }
        
        //获取当前短信配置
        $sms_config    = ConfigChannel::instance()->info(['code' => 'sms_wwtl','cid'=>$param['cid']]);
        
        if (!$sms_config||$sms_config['is_config']==0) {
            return Normal::returnCode(Normal::FAIL,"发送失败[undefined sms_config]");
        }
        $sms_config['value']= json_decode($sms_config['value'],true);
        $param['code'] = \app\common\service\Helper\Str::random(6, '0123456789');
        $res = Sms::instance($sms_config)->sendMessage($param);

        if ($res['code'] != Normal::SUC) {
            return $res;
        }
        
        $data = [
            'mobile' => $param['mobile'],
            'code'   => $param['code'],
            'cd'     => time(),
            'cid'   =>$param['cid']
        ];
        
        SmsCode::instance()->add($data);
        
        //发送次数存入缓存
        $send_times++;
        $redis->set($cache_key, $send_times, 60);
        return Normal::returnCode(Normal::SUC,"发送成功");
    }
}